<?php

namespace App\Observers;

use App\Models\Reply;
use App\Notifications\TopicReplied;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class ReplyObserver
{

    public function creating(Reply $reply)
    {
        $reply->content = clean($reply->content, 'user_topic_body');
    }

    public function created(Reply $reply)
    {
        $reply->topic->updateReplyCount();
        // 通知话题作者有新的评论(自己不通知)
        if ($reply->user_id !== $reply->topic->user_uid) {
            $reply->topic->user->notify(new TopicReplied($reply));
        }
        // 更新最后回复用户
        if (auth()->check()) {
            $reply->topic->last_reply_user_id = intval(auth()->id());
            $reply->topic->save();
        }
    }

    public function deleted(Reply $reply)
    {
        $reply->topic->updateReplyCount();
    }
}
